<?php

namespace App\Http\Controllers\Resources;

use App\Models\Project;
use App\Models\Role;
use App\Models\Group;
use App\Models\User;
use App\Services\ServiceFactory;
use Helper;
use App\Models\Company;
use App\Plugins\Sms\SendInfo;
use Auth;
use Log;
use App\Http\Requests;
use App\Http\Requests\UserRequest;
use App\Services\Interfaces\RepoServiceInterface;
use App\Http\Controllers\Controller;
use App\Jobs\SendUserInfo;

class UserController extends Controller
{
    public function __construct($_resource)
    {
        $this->_resource = $_resource;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //当前登录用户为操作员的话,无权限创建
        //$this->authorize(new User());
        $res_data = $this->_repoService()->read();
        return $res_data;

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //当前登录用户为操作员的话,无权限创建
        $this->authorize('create', new User());
    }

    /**
     * 新增账户
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request)
    {
        try {
            $data = [];
            foreach (User::InputFiled as $key => $default) {
                $data[$key] = $request->input($key, $default);
            }
            $user = Auth::user();
            //验证权限与部门
            if (!Role::find($data['role_id'])) {
                return $this->_error('权限不存在');
            }
            if (!Group::find($data['group_id'])) {
                return $this->_error('部门不存在');
            }
            $password = str_random(6);
            $data['password'] = $password;
            $groups = Group::all();
            $new_groups = new Group();
            //创建的账号的时候会选择一个组织架构，当前登陆的账号只能创建子集以及当前级别的账号
            $group_data = $new_groups->getTree($groups, $user['group_id']);//获取当前group_id下的所有直系下属数据
            $group_ids = [$user['group_id']];
            $alias = Company::where('_id',$user->company_id)->pluck('alias')->all()[0];
            foreach ($group_data as $k => $v) {
                array_push($group_ids, $v['id']);
            }
            if (in_array($data['group_id'], $group_ids)) {
                $res = $this->_repoService()->create($data);
                $sendData = [
                    'password' => $password,
                    'mobile' =>$data['mobile'],
                    'alias' =>$alias
                ];
                $job = new SendUserInfo($sendData);
                dispatch($job);
                return $res;
            } else {
                return $this->_error('创建失败');
            }
        } catch (\Exception $ex) {
            // todo write error to log
            Log::info($ex);
            if (config('app.debug')) {
                throw $ex;
            }
        }
    }

    /**
     * 账户详情
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //当前登录用户为操作员的话,无权限创建
        //$this->authorize('show', new User());
        $result = $this->_repoService()->find(['id' => $id]);
        $user = Auth::User();
        if ($result->company_id == $user->company_id) {
            return $result;
        } else {
            return $this->_error('没有指定用户');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //当前登录用户为操作员的话,无权限创建
        $this->authorize('edit', new User());
    }

    /**
     * 修改账户及禁用账户
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserRequest $request, $id)
    {
        if ($request->method() == 'PUT') {
            $update_data = $request->all();
            $users = User::find($id);
            if (!empty($users)) {
                if (isset($update_data['group_id'])
                    && $update_data['group_id'] !== $users->group_id
                ) {
                    $old_project = Project::where('group_id', $users->group_id)->first();
                    $new_project = Project::where('group_id', $update_data['group_id'])->first();
                    if (!is_null($old_project)) {
                        $users_id = $old_project->users;
                        if (($key = array_search($users->_id, $users_id)) !== false) {
                            unset($users_id[$key]);
                            $old_project->users =
                                array_values($users_id);
                            $old_project->save();
                        }
                    }
                    if (!is_null($new_project)) {
                        $users_id = $new_project->users;
                        array_push($users_id, $users->_id);
                        $new_project->users = $users_id;
                        $new_project->save();
                    }
                }
                $this->_repoService()->update(['_id' => $id], $update_data);
//                User::where('_id', $id)->update(
//                    [
//                        'name' => empty($update_data['name']) ? $users->name : $update_data['name'],
//                        'mobile' => empty($update_data['mobile']) ? $users->mobile : $update_data['mobile'],
//                        'email' => empty($update_data['email']) ? $users->email : $update_data['email'],
//                        'position' => empty($update_data['position']) ? $users->position : $update_data['position'],
//                        'group_id' => empty($update_data['group_id']) ? $users->group_id : $update_data['group_id'],
//                        'isManager' => empty($update_data['isManager']) ? $users->isManager : $update_data['isManager'],
//                        'role_id' => empty($update_data['role_id']) ? $users->role_id : $update_data['role_id'],
//                    ]
//                );
            }
        } elseif ($request->method() == 'PATCH') {
            $status = $request->all();
            if (!User::where('_id', $id)->update(['status' => $status['status']])) {
                return $this->_error('failed');
            }
        }
        return $this->show($id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //当前登录用户为操作员的话,无权限创建
        $this->authorize('destroy', new User());
    }
}
